package com.fxp.project.jiuselu.web.models.withdrawal.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fxp.project.jiuselu.commons.constant.ConstantCode;
import com.fxp.project.jiuselu.commons.exceptions.JiuLuException;
import com.fxp.project.jiuselu.web.models.user.entity.JslUser;
import com.fxp.project.jiuselu.web.models.user.service.IJslUserService;
import com.fxp.project.jiuselu.web.models.withdrawal.entity.JslUserWithdrawalRecord;
import com.fxp.project.jiuselu.web.models.withdrawal.mapper.JslUserWithdrawalRecordMapper;
import com.fxp.project.jiuselu.web.models.withdrawal.qo.ApplyWithdrawalQo;
import com.fxp.project.jiuselu.web.models.withdrawal.service.IJslUserWithdrawalRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * <p>
 * 用户提现记录表 服务实现类
 * </p>
 *
 * @author Jason.Wang
 * @since 2022-01-09
 */
@Service
public class JslUserWithdrawalRecordServiceImpl extends ServiceImpl<JslUserWithdrawalRecordMapper, JslUserWithdrawalRecord> implements IJslUserWithdrawalRecordService {

    @Autowired
    private IJslUserService iJslUserService ;
    @Autowired
    private JslUserWithdrawalRecordMapper jslUserWithdrawalRecordMapper ;

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void applyWithdrawal(ApplyWithdrawalQo applyWithdrawalQo, Long userId) {
        JslUser user = iJslUserService.getById(userId);
        if( null == user){
            throw new JiuLuException(ConstantCode.SYSTEM_EXCEPTION.getCode(), "当前用户不存在");
        }
        if (user.getUserMoney().compareTo(applyWithdrawalQo.getAmount()) == -1){
            throw new JiuLuException(ConstantCode.SYSTEM_EXCEPTION.getCode(), "用户可提现金额不足");
        }
        user.setUserMoney(user.getUserMoney().subtract(applyWithdrawalQo.getAmount()));
        user.setFrozenMoney(user.getFrozenMoney().add(applyWithdrawalQo.getAmount()));
        iJslUserService.updateById(user);

        JslUserWithdrawalRecord record = new JslUserWithdrawalRecord();
        record.setUserId(userId);
        record.setBankCardId(applyWithdrawalQo.getBankCardId());
        record.setApplyTime(LocalDateTime.now());
        record.setStatus(0);
        record.setAmount(applyWithdrawalQo.getAmount());
        jslUserWithdrawalRecordMapper.insert(record);
    }
}
